<template>
  <basic-container>
    <el-page-header @back="handleBack" :content="obj.courseName" /><el-divider />
    <el-tabs tab-position="left" @tab-click="onCurrentTabChange">
      <el-tab-pane>
        <span slot="label" style="font-size: 16px">
          <i class="el-icon-user"/>&nbsp;成员管理
        </span>
        <avue-crud ref="crud-member"
                   :option="memberOption"
                   :table-loading="loading"
                   :data="memberData"
                   :page="page"
                   :permission="permissionList">
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane>
        <span slot="label" style="font-size: 16px">
          <i class="el-icon-coordinate"/>&nbsp;考勤管理
        </span>
        <avue-crud ref="crud-attendance"
                   :option="attendanceOption"
                   :table-loading="loading"
                   :data="attendanceDate"
                   :page="page"
                   :permission="permissionList"
                   @row-save="rowAttendanceSave">
          <template slot="menuLeft">
            <el-button type="primary"
                       size="small"
                       icon="el-icon-plus"
                       plain
                       @click="handleAttendanceAdd">新 增
            </el-button>
          </template>
          <template slot="menu" slot-scope="scope">
            <el-button type="text" size="small">
              <el-dropdown type="primary" size="small" :visible-change="() => {

              }">
                <span class="el-dropdown-link">
                  更 多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu type="primary" slot="dropdown">
                  <el-dropdown-item
                    icon="el-icon-location-information"
                    @click.native="handleSign(scope.row)">签 到
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane>
        <span slot="label" style="font-size: 16px">
          <i class="el-icon-reading"/>&nbsp;作业管理
        </span>
        <avue-crud ref="crud-homework"
                   :option="homeworkOption"
                   :table-loading="loading"
                   :data="homeworkDate"
                   :page="page"
                   :permission="permissionList">
          <template slot="menuLeft">
            <el-button type="primary"
                       size="small"
                       icon="el-icon-plus"
                       plain
                       @click="handleHomeworkAdd">新 增
            </el-button>
          </template>
          <template slot="menu" slot-scope="scope">
            <el-button type="text" size="small">
              <el-dropdown type="primary" size="small">
                <span class="el-dropdown-link">
                  更 多<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu type="primary" slot="dropdown">
                  <el-dropdown-item
                    icon="el-icon-finished"
                    @click.native="handleCheck(scope.row)">验 收
                  </el-dropdown-item>
                  <el-dropdown-item
                    icon="el-icon-document-checked"
                    @click.native="handleScore(scope.row)">评 分
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-button>
          </template>
        </avue-crud>
      </el-tab-pane>
      <el-tab-pane>
        <span slot="label" style="font-size: 16px">
          <i class="el-icon-data-line"/>&nbsp;成绩管理
        </span>
        成绩管理
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="签 到"
               :visible.sync="dialogSignVisible"
               width="40%"
               :close-on-click-modal="false"
               :before-close="handleDialogBeforeClose">
      <el-transfer :titles="['未签到', '已签到']"
                   filterable
                   v-model="signValue"
                   :data="signData"
                   :render-content="transferFunc">
      </el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSignVisible = false">
          取 消
        </el-button>
        <el-button type="primary" :loading="submitBtnLoading" @click="handleSignSubmit">
          保 存
        </el-button>
      </span>
    </el-dialog>

    <el-dialog title="验 收"
               :visible.sync="dialogCheckVisible"
               width="40%"
               :close-on-click-modal="false"
               :before-close="handleDialogBeforeClose">
      <el-transfer :titles="['未提交', '已提交']"
                   filterable
                   v-model="checkValue"
                   :data="checkData"
                   :render-content="transferFunc">
      </el-transfer>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogCheckVisible = false">
          取 消
        </el-button>
        <el-button type="primary" :loading="submitBtnLoading" @click="handleCheckSubmit">
          保 存
        </el-button>
      </span>
    </el-dialog>

    <el-dialog title="评 分"
               :visible.sync="dialogScoreVisible"
               width="50%"
               :close-on-click-modal="false">
      <avue-crud :option="scoreOption"
                 :table-loading="dialogLoading"
                 :data="scoreDate"
                 :page="scorePage"
                 :permission="permissionList"
                 ref="crud-dialog-score"
                 @on-load="onScoreLoad">
        <template slot="menuLeft">
          <el-button type="primary"
                     size="small"
                     icon="el-icon-edit"
                     plain
                     v-show="!scoreType"
                     @click="editAllScoreBtn">编 辑
          </el-button>
          <el-button type="success"
                     size="small"
                     icon="el-icon-circle-plus-outline"
                     plain
                     v-show="scoreType"
                     @click="saveAllScoreBtn">保 存
          </el-button>
          <el-button type="warning"
                     size="small"
                     icon="el-icon-circle-close"
                     plain
                     v-show="scoreType"
                     @click="cancelAllScoreBtn">取 消
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getSignDataList, getSignedList, signSubmit} from "@/api/education/mapper/attendancedetail";
  import {getCheckDataList, getSubmittedList, checkSubmit, getScoreDataList, updateScoreData} from "@/api/education/mapper/homeworkdetail";
  import {getMemberList, getAttendanceList, getHomeworkList} from "@/api/education/mapper/classroomdetails"
  import {goBackChange} from "@/util/util";
  import {memberOption, attendanceOption, homeworkOption, gradesOption, scoreOption} from "@/const/crud/education/mapper/classroomdetails";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        obj: {
          courseId: '',
          courseName: '',
        },
        loading: false,
        dialogLoading: false,
        submitBtnLoading: false,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        scorePage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        query: {},
        memberData: [],
        memberOption: memberOption,
        attendanceDate: [],
        attendanceOption: attendanceOption,
        homeworkDate: [],
        homeworkOption: homeworkOption,
        gradesDate: [],
        // TODO
        gradesOption: gradesOption,
        scoreType: false,
        scoreOption: scoreOption,
        scoreDate: [],
        dialogSignVisible: false,
        signValue: [],
        signData: [],
        dialogCheckVisible: false,
        checkValue: [],
        checkData: [],
        dialogScoreVisible: false,
        attendanceId: undefined,
        homeworkId: undefined
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.course_add, false),
          viewBtn: this.vaildData(this.permission.course_view, false),
          delBtn: this.vaildData(this.permission.course_delete, false),
          editBtn: this.vaildData(this.permission.course_edit, false)
        };
      }
    },
    created() {
      this.obj.courseId = this.$route.query.id;
      this.obj.courseName = decodeURIComponent(this.$route.query.courseName);
      this.handleMember(this.page, {courseId: this.obj.courseId});
    },
    watch: {
      scoreType(newVal, oldVal) {
        if (this.scoreDate.length > 0) {
          this.scoreDate.forEach(item => item.$cellEdit = newVal);
        }
      }
    },
    methods: {
      handleBack() {
        goBackChange(this.$router)
      },
      onCurrentTabChange(val) {
        let params = {
          courseId: this.obj.courseId
        };
        this.page = {
          pageSize: 10,
          currentPage: 1,
          total: 0
        };
        this.query = {};
        switch (val.index) {
          case "0":
            this.handleMember(this.page, params);
            break;
          case "1":
            this.handleAttendance(this.page, params);
            break;
          case "2":
            this.handleHomework(this.page, params);
            break;
          case "3":
            this.handleGrades(this.page, params);
        }
      },
      handleMember(page, params) {
        this.loading = true;
        getMemberList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query)
        ).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.memberData = data.records;
          this.loading = false;
        })
      },
      handleAttendance(page, params = {}) {
        this.loading = true;
        getAttendanceList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query)
        ).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.attendanceDate = data.records;
          this.loading = false;
        })
      },
      handleHomework(page, params = {}) {
        this.loading = true;
        getHomeworkList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query)
        ).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.homeworkDate = data.records;
          this.loading = false;
        })
      },
      handleGrades(page, params = {}) {

      },
      handleAttendanceAdd() {
        this.$refs['crud-attendance'].rowAdd();
      },
      handleHomeworkAdd() {
        this.$refs['crud-homework'].rowAdd();
      },
      handleSign(row) {
        this.attendanceId = row.id;
        this.loading = true;
        this.submitBtnLoading = false;
        let _this = this;
        let fun1 = new Promise((resolve, reject) => {
          _this.signData = [];
          getSignDataList({
            courseId: _this.obj.courseId
          }).then(res => {
            const data = res.data.data;
            data.forEach(item => {
              _this.signData.push({
                key: item.id,
                label: item.realName,
              });
            })
            resolve();
          });
        });
        let fun2 = new Promise((resolve, reject) => {
          _this.signValue = [];
          getSignedList({
            attendanceId: _this.attendanceId
          }).then(res => {
            const data = res.data.data;
            data.forEach(item => {
              _this.signValue.push(item.id)
            })
            resolve();
          });
        });
        Promise.all([fun1, fun2]).then(() => {
          _this.loading = false;
          _this.dialogSignVisible = true;
        })
      },
      handleSignSubmit() {
        let _this = this;
        _this.submitBtnLoading = true;
        signSubmit(Object.assign({
          attendanceId: _this.attendanceId,
          studentIdList: _this.signValue
        })).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          _this.dialogSignVisible = false;
        }).finally(() => {
          _this.submitBtnLoading = false;
        });
      },
      handleCheck(row) {
        this.homeworkId = row.id;
        this.loading = true;
        let _this = this;
        let fun1 = new Promise((resolve, reject) => {
          _this.checkData = [];
          getCheckDataList({
            courseId: _this.obj.courseId
          }).then(res => {
            const data = res.data.data;
            data.forEach(item => {
              _this.checkData.push({
                key: item.id,
                label: item.realName,
              });
            })
            resolve();
          });
        });
        let fun2 = new Promise((resolve, reject) => {
          _this.checkValue = [];
          getSubmittedList({
            homeworkId: _this.homeworkId
          }).then(res => {
            const data = res.data.data;
            data.forEach(item => {
              _this.checkValue.push(item.id)
            })
            resolve();
          });
        });
        Promise.all([fun1, fun2]).then(() => {
          _this.loading = false;
          _this.dialogCheckVisible = true;
        })
      },
      handleCheckSubmit() {
        let _this = this;
        _this.submitBtnLoading = true;
        checkSubmit(Object.assign({
          homeworkId: _this.homeworkId,
          studentIdList: _this.checkValue
        })).then(() => {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          _this.dialogCheckVisible = false;
        }).finally(() => {
          _this.submitBtnLoading = false;
        });
      },
      handleScore(row) {
        this.homeworkId = row.id;
        this.scoreType = false;
        this.dialogScoreVisible = true;
      },
      editAllScoreBtn() {
        this.scoreType = true;
      },
      saveAllScoreBtn() {
        this.dialogLoading = true;
        let obj = []
        this.scoreDate.forEach(item => {
          obj.push({
            id: item.id,
            score: item.score
          })
        });
        updateScoreData(obj).then(res => {
          const data = res.data;
          if (data.success) {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.scoreType = false;
          } else {
            this.$message({
              type: "error",
              message: res.data.msg
            });
          }
        }).finally(() => {
          this.dialogLoading = false
        });
      },
      cancelAllScoreBtn() {
        this.scoreType = false;
        this.onScoreLoad(this.scorePage);
      },
      onScoreLoad(page, params = {}) {
        this.dialogLoading = true;
        getScoreDataList(
          page.currentPage,
          page.pageSize,
          Object.assign({homeworkId: this.homeworkId}, params)
        ).then(res => {
          const data = res.data.data;
          this.scorePage.total = data.total;
          data.records.forEach(item => item.$cellEdit = false);
          this.scoreDate = data.records;
        }).finally(() => {
          this.dialogLoading = false;
        });
      },
      handleDialogBeforeClose(done) {
        this.$confirm("关闭窗口数据将会丢失，确定关闭?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          done();
        });
      },
      rowAttendanceSave(row, done, loading) {

      },
      transferFunc(h, option) {
        return this.h(this.signValue, h, option);
      },
      h(modelV, h, option) {
        return h(
          'span', {
            attrs: {
              id: option.label
            },
            domProps: {
              innerHTML: option.label
            },
            on: {
              "click": () => {
                //简单的逻辑  如果不在 v-model值数组里面，则push，否则从数组中删除
                if (modelV.includes(option.key)) {
                  let index = modelV.indexOf(option.key)
                  modelV.splice(index, 1);
                } else {
                  modelV.push(option.key)
                }
              }
            }
          }
        )
      },
    }
  }
</script>

<style lang="scss" scoped>

.el-page-header {
  padding: 10px 24px 0 24px;
}

.el-select-dropdown {
  width: 100%;
  .el-scrollbar {
    .el-select-dropdown__wrap {
      margin: 0 !important;
    }
  }
}
.el-dropdown-link {
  cursor: pointer;
  font-size: 12px;
  color: #409EFF;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.el-transfer {
  /deep/ .el-transfer-panel{
    height: 700px;
    width: 35%;
  }
  /deep/ .el-transfer__buttons {
    margin: auto 0;
  }
  /deep/ .el-transfer-panel__list.is-filterable{
    height: 600px;
  }
}
</style>
